import * as cc from 'cc';
const { ccclass, property } = cc._decorator;
@ccclass('HelloWorld')
export class HelloWorld extends cc.Component {
    //当前页面，用预制体实例化页面，代替Scene
    pageNode: cc.Node = null;
    //翻页特效节点
    turnEffectNode: cc.Node = null;
    //标记是否正在翻页
    isTurnning: boolean = false;
    start() {
        cc.profiler.hideStats();
        this.turnEffectNode = this.node.getChildByName('TurnEffect');
        this.setPage('Res/页面A', 'MaskFade');
        this.node.on(cc.Node.EventType.TOUCH_START, () => {
            this.setPage(`Res/${this.randomValue(['页面A', '页面B', '页面C'])}`, this.randomValue(['MaskFade', 'Curtain', 'CurtainH', 'CurtainV']));
        }, this);
    }
    //返回数组、对象、Map中的随机元素
    randomValue(obj: any): any {
        switch (obj.__proto__.constructor) {
            case Array: return obj[~~(Math.random() * obj.length)];
            case Object: return this.randomValue(Object['values'](obj));
            case Map: return this.randomValue(Array.from(obj.values()));
        }
    }
    //加载资源，需填写完整路径（BundleName / FileName）
    loadAsync(path: string): Promise<any> {
        return new Promise<any>((resolve) => {
            let index = path.indexOf('/');
            let bundleName = path.substring(0, index);
            let filePath = path.substring(index + 1);
            cc.assetManager.loadBundle(bundleName, (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) { cc.error(`loadAsync加载Bundle失败！(${bundleName})`); resolve(null); return; }
                let files = bundle.getDirWithPath('');
                let type = cc.Prefab;
                for (let i = files.length - 1; i > -1; --i) {
                    if (filePath === files[i].path) { type = files[i].ctor.prototype.constructor; break; }
                }
                bundle.load(filePath, type, (err: Error, asset: any) => {
                    if (err) { cc.error(`loadAsync加载资源失败！(${path})`); resolve(null); return; }
                    resolve(asset); return;
                });
            });
        });
    }
    // 翻页，流程如下：
    // Step 1：播放名称为turnEffectName的翻页动画
    // Step 2：移除旧页面，添加新页面（名称为name的预制体）
    // Step 3：把翻页动画反着播，完成翻页
    setPage(name: string, turnEffectName?: string) {
        let trans = async () => {
            if (cc.isValid(this.pageNode)) {
                this.pageNode.removeFromParent();
                this.pageNode.destroy();
            }
            this.pageNode = cc.instantiate(await this.loadAsync(name));
            this.pageNode.setParent(this.node);
            this.pageNode.setSiblingIndex(1);
        }
        if (!turnEffectName) { trans(); this.isTurnning = false; return }
        if (this.isTurnning) return;  //翻页过程中无法再次翻页
        this.isTurnning = true;
        let model = this.turnEffectNode.getComponent(cc.Animation);
        let state = model.getState(turnEffectName);
        if (!state) { trans(); this.isTurnning = false; return }
        model.off(cc.Animation.EventType.FINISHED);
        model.on(cc.Animation.EventType.FINISHED, async () => {
            if (state.wrapMode === cc.AnimationClip.WrapMode.Normal) {
                await trans();
                state.wrapMode = cc.AnimationClip.WrapMode.Reverse;
                state.play();
            } else {
                this.isTurnning = false;
            }
        });
        state.wrapMode = cc.AnimationClip.WrapMode.Normal;
        state.play();
    }
}